package desktop;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

class StorageManager {
    private int N_MATCH;
    private List<Screen> screens;
    private List<ScoreTable> scoreTables;
    private JLabel image;
    private JTextField matchName_input;
    private List<SetTeamName> setTeamNames;

    StorageManager(List<ScoreTable> scoreTables, List<Screen> screens, int n_match, JLabel image, JTextField matchName_input, List<SetTeamName> setTeamNames){
        this.scoreTables = scoreTables;
        this.screens = screens;
        N_MATCH = n_match;
        this.image = image;
        this.matchName_input = matchName_input;
        this.setTeamNames = setTeamNames;
    }

    void save(){ //T红F黄
        List<Score> scores = new ArrayList<>();
        for(int i=0;i<scoreTables.size();i++) {
            for(int j=1;j<=N_MATCH;j++) {
                Score score1 = new Score();
                score1.screen = i+1; //记录人类习惯的数字，从1开始
                score1.match = j;
                score1.team = true;
                score1.score = scoreTables.get(i).getScore(true, j); //红队
                scores.add(score1);
                Score score2 = new Score();
                score2.screen = i+1; //记录人类习惯的数字，从1开始
                score2.match = j;
                score2.team = false;
                score2.score = scoreTables.get(i).getScore(false, j); //黄队
                scores.add(score2);
            }
        }
        //分数提取成功，下面开始提取配置
        List<String> groups = new ArrayList<>();
        List<String> team1s = new ArrayList<>();
        List<String> team2s = new ArrayList<>();
        for(Screen screen: screens){
            groups.add(screen.getGroupName());
            team1s.add(screen.getTeam1Name());
            team2s.add(screen.getTeam2Name());
        }

        JFileChooser jfc = new JFileChooser(); //打开文件选择窗口
        FileNameExtensionFilter filter = new FileNameExtensionFilter("配置文件(*.peConf)", "peConf");
        jfc.setFileFilter(filter); //后缀名过滤器
        int option = jfc.showSaveDialog(null);
        File file;
        if(JFileChooser.APPROVE_OPTION == option) {
            String path = jfc.getSelectedFile().getAbsolutePath();
            if(path.contains(".peConf"))
                file = jfc.getSelectedFile();
            else
                file = new File(path+".peConf");
        }else
            return;

        try {
            FileOutputStream fos = new FileOutputStream(file); //创建FileOutputStream对象，写入内容
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Store store = new Store(screens.get(0).getMatchTitle(), screens.get(0).getImageIcon(),groups, team1s, team2s, scores);
            oos.writeObject(store);
            oos.close();
            fos.close();
            JOptionPane.showMessageDialog(null,"配置及分数信息保存完毕！","保存",JOptionPane.INFORMATION_MESSAGE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    void reload(){ //还原配置及分数信息
        String dir = "";
        JFileChooser jfc = new JFileChooser(); // 打开文件选择窗口
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                String extension = f.getName().substring(f.getName().lastIndexOf(".")+1);
                return (extension.equals("peConf"));
            }

            @Override
            public String getDescription() {
                return "配置文件(*.peConf)";
            }
        });
        jfc.showDialog(new JLabel(), "选择");
        if(jfc.getSelectedFile()!=null)
           dir = jfc.getSelectedFile().getAbsolutePath();
        else
            return;

        try {
            File file = new File(dir);
            FileInputStream fis = new FileInputStream(file); //创建FileInputStream对象，写入内容
            ObjectInputStream ois = new ObjectInputStream(fis);
            Store store = (Store) ois.readObject();
            for(int i=0;i<screens.size();i++) {
                Screen screen = screens.get(i);
                screen.setMatchName(store.matchName); //恢复比赛名称
                screen.setPicIcon(store.imageIcon); //恢复比赛图标
                screen.setGroupName(store.groups.get(i)); //恢复组名
                setTeamNames.get(i).setGroupName(store.groups.get(i));
                screen.setTeam1Name(store.team1.get(i)); //恢复红队名
                setTeamNames.get(i).setTeam1Name(store.team1.get(i));
                screen.setTeam2Name(store.team2.get(i)); //恢复黄队名
                setTeamNames.get(i).setTeam2Name(store.team2.get(i));
            }
            image.setIcon(store.imageIcon); //设置裁判盒中的比赛图标
            matchName_input.setText(store.matchName); //设置裁判盒中的比赛名称
            //恢复分数
            List<Score> scores = store.scores;
            for(Score score: scores) {
                if(score.score!=0) {
                    scoreTables.get(score.screen - 1).updateScore(score.team, score.match, score.score);
                    screens.get(score.screen - 1).setScore(score.team,score.match,score.score);
                }
            }
            ois.close();
            fis.close();
            JOptionPane.showMessageDialog(null,"配置及分数信息还原完毕！","还原",JOptionPane.INFORMATION_MESSAGE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    static class Store implements Serializable {
        private String matchName;
        private Icon imageIcon;
        private List<String> groups;
        private List<String> team1;
        private List<String> team2;
        private List<Score> scores;

        Store(String matchName, Icon imageIcon, List<String> groups, List<String> team1, List<String> team2, List<Score> scores){
            this.matchName = matchName;
            this.imageIcon = imageIcon;
            this.groups = groups;
            this.team1 = team1;
            this.team2 = team2;
            this.scores = scores;
        }
    }
}
